<template>
  <div class="content">
    <div class="left">
      <div class="tab-content">{{ $t('rpm.title.project') }}</div>
      <div class="project-switch-content">
        <el-tooltip
          v-bind="{
            content: tooltipText,
            effect: 'dark',
            popperClass: 'displayname-tooltip',
            placement: 'top'
          }"
        >
          <ty-plm-select
            v-model="projectOid"
            :options="{
              list: list,
              loading: loading,
              props: { value: 'oid', label: 'displayName' },
              showArrow: true,
              popperClass: 'project-list-option',
              valueKey: 'oid',
              placeholder: $t('basic.placeholder.plsSelect'),
              loadingText: $t('basic.placeholder.searchLoading'),
              popperAppendToBody: false
            }"
            @visible-change="visibleChange"
          >
            <template #header>
              <ty-plm-input
                v-model="keyWord"
                :options="{ placeholder: $t('plsInKw'), clearable: true }"
                @keyup.enter="getProjectList"
                :suffix-icon="Search"
                style="width: 100%"
              ></ty-plm-input>
            </template>
            <template #default="{ data }">
              <el-tooltip
                v-bind="{
                  content: data.displayName,
                  effect: 'dark',
                  popperClass: 'displayname-tooltip',
                  placement: 'top'
                }"
              >
                <span class="list-label" @click="changeProject(data)">{{ data.displayName }}</span>
              </el-tooltip>

              <em
                @click.stop="handleStar(data)"
                :class="
                  data.starred
                    ? 'iconfont icon-xingxing shoucangIcon list-shoucang'
                    : 'iconfont icon-xingxing1 list-shoucang '
                "
              ></em>
            </template>
            <template #footer>
              <em class="iconfont icon-liebiao2"></em>
              <span v-html="totalMessage" class="link-span" @click="jumpToMyproject"></span>
            </template>
          </ty-plm-select>
        </el-tooltip>
      </div>
      <div class="collection-content">
        <em :class="preSelectObject.starred ? 'iconfont icon-xingxing shoucangIcon' : 'iconfont icon-xingxing1'"
          @click.stop="handleStar(preSelectObject)"></em>
        <div class="tag" :style="statuss[status]?.style || {}">
          <!-- {{ statusOptions[preSelectObject.completionStatus]?.label || '' }} -->
            {{ status ||"" }}
          <!-- {{ statusOptions[row.completionStatus]?.label || '' }} -->
        </div>
        <ty-plm-tag :type="healthTagtype" :title="preSelectObject.healthStatusName"></ty-plm-tag>
        <div class="total-days-title">{{ daysTotal }}</div>
      </div>
    </div>

    <div class="operate-content">
      <div
        v-for="btn in btnLists"
        :key="btn.value"
        class="operate-btn"
        @click="hanlebtnFunc(btn)"
        :class="getDisabled(btn.key) ? 'disable-btn' : ''"
      >
        <template v-if="!btn.hidden && !getDisabled(btn.key)">
          <em class="icon" :class="btn.iconfont"></em>
          <div class="title">{{ btn.key }}</div>
        </template>
      </div>
    </div>
  </div>
  <ty-plm-dialog v-model="showProject" :options="projectEditOptions" @doConfirm="doConfirm">
    <project-edit ref="projectEditRef" :projectDetail="projectDetail"></project-edit>
  </ty-plm-dialog>
</template>
<script setup>
import { ElMessage } from 'element-plus'
// import { funcIndex, useOverride } from '../composables/tag-index.js'; //正常导入
// import ProjectEdit from '@modules/rpm/business-module/project/components/project-edit'; 页面
import { Search } from '@element-plus/icons-vue';
import { ref,watch,onMounted } from 'vue';

const ProjectEdit = tyRoot.getExportResource(
  'src/modules/rpm/business-module/project/components/project-edit.vue'
).default;
const {funcIndex} = window.tyRoot.getExportResource(
  'src/modules/rpm/business-module/project-infor-panel/composables/tag-index.js'
);
const { useOverride} = window.tyRoot.getExportResource(
  'src/modules/rpm/business-module/project-infor-panel/composables/tag-index.js'
);
import core from '@common/core'
import axios from 'axios';
const request = core.getExportResource('src/core/utils/http-tools.js').default;

defineOptions({
  name: 'projectTag'
});
onMounted(() => {
  getStatus();
})
const statuss = ({
    '编制中': {
      label: '编制中',
      style: {
        color: '#055DD5',
        backgroundColor: '#E7F3FE',
        borderColor: '#66B5FE'
      }
    },
    '未启动': {
      label: '未启动',
      style: {
        color: '#FA8C14',
        backgroundColor: '#FFF7E6',
        borderColor: '#FFA940'
      }
    },
    '正常': {
      label: '正常',
      style: {
        color: '#14AD30',
        backgroundColor: '#EDFFEE',
        borderColor: '#64D26D'
      }
    },
    '延期': {
      label: '延期',
      style: {
        color: '#FA8C14',
        backgroundColor: '#FFF7E6',
        borderColor: '#FFA940'
      }
    },
    // '默认状态': {
    //   label: '默认状态',
    //   style: {
    //     color: '#999',
    //     backgroundColor: '#F5F5F5',
    //     borderColor: '#D9D9D9'
    //   }
    // },
    '完成': {
      label: '完成',
      style: {
        color: '#0B6623',
        backgroundColor: '#C8E6C9',
        borderColor: '#4CAF50'
      }
    },
    '预延期': {
      label: '预延期',
      style: {
        color: '#FA8C14',
        backgroundColor: '#FFF7E6',
        borderColor: '#FFA940'
      }
    },
    '暂停': {
      label: '暂停',
      style: {
        color: '#B8860B',
        backgroundColor: '#FFF3CD',
        borderColor: '#FFC107'
      }
    },
    '延期完成': {
      label: '延期完成',
      style: {
        color: '#7B61FF',      // 深紫色文字
        backgroundColor: '#F3F0FF',  // 淡紫色背景
        borderColor: '#C9BFFF'   // 中紫色边框
      }
    }
  });

const status = ref('')
async function getStatus() {
  let data = sessionStorage.getItem('obj')
  let obj = JSON.parse(data)
  let oid = obj.oidAndLogicalList[0].oid
  let res = await axios('/rest/v1/iba/getAttrValueTableByEntitys', {
    method: 'post',
    data: obj,
    headers: {
      authorization: sessionStorage.getItem('authorization')
    }
  })
  let temp = res.data.data[oid]
  status.value = temp["执行状态"][0]
}
const {
  projectOid,
  loading,
  keyWord,
  visibleChange,
  getProjectList,
  handleStar,
  jumpToMyproject,
  preSelectObject,
  healthTagtype,
  changeProject,
  list,
  listTotal,
  btnList,
  getDisabled,
  totalMessage,
  daysTotal,
  btnFunc,
  showProject,
  projectEditRef,
  projectEditOptions,
  projectDetail,
  doConfirm,
  statusOptions,
  tooltipText
} = (useOverride || funcIndex)();
// let isbtn = "";
const hanlebtnFunc = (btn) => {
  // isbtn = btn.key;
  if(btn.key =="暂停"){
    let params = {
      params:{},
      changeReason:"",
      projectId:projectOid.value, //项目oid
      type:"项目暂停",
    };
    postOAData(params)
      .then((res) => {
      if(!res.data.data){
        ElMessage.error(res.data.message);
        return;
      }
        window.open(`${res.data.data}`, "_blank");
      })
      .catch((error) => {
        {
          console.error("获取数据失败:", error);
          this.$message.error("数据有误，请稍后重试");
          // 如果接口失败，保持空数组
        }
      });
  }else if(btn.key =="恢复启动"){
    let params = {
      params:{},
      changeReason:"",
      projectId:projectOid.value, //项目oid
      type:"项目恢复",
    };
    postOAData(params)
      .then((res) => {
      if(!res.data.data){
        ElMessage.error(res.data.message);
        return;
      }
        window.open(`${res.data.data}`, "_blank");
      })
      .catch((error) => {
        {
          console.error("获取数据失败:", error);
          this.$message.error("数据有误，请稍后重试");
          // 如果接口失败，保持空数组
        }
      });
  }
  else{
  btnFunc(btn);
  }
};

const postOAData = (data) => {
  return request({
    method: 'post',
    data: {
      projectOID: data.projectId,
      type: data.type
    },
    url: `/typrjmng/api/v1/change/projectStopOrReStart?projectId=${encodeURIComponent(data.projectId)}&type=${encodeURIComponent(data.type)}`,
    headers: {
      'Content-Type': 'application/json'
    }
  })
    .then((res) => {
      return res;
    })
    .catch((e) => {
      proxy.$message.error(e?.message || '查询失败');
    });
};
let btnLists = [];
watch(
  () => btnList.value,
  (newValue) => {
    btnLists = newValue.filter(item => item.key !== "启动" && item.key !== "终止");
    console.log("btnList 变化后的值：",btnLists);
  },
  { immediate: true } // 立即执行一次
);
// // 定义 watch 侦听器监听数组变化
// watch(
//   btnList, // 数据源（ref对象）
//   (newVal, oldVal) => {
//     //初始化传入数据
//     let params = {
//       params:{
//   // activeList:projectDetail.value.planActiveList,
//   // changeNo:"",
//   // content:{
//   //   planFinishDate:projectDetail.value.plan.finishDate,
//   //   planStartDate:projectDetail.value.plan.startDate
//   // },
//   // description:"",
//   // planActiveDTO:[],
//   // planoid:projectDetail.value.plan.oid,
//   // planotype:projectDetail.value.plan.otype,
//   // projectoid:projectDetail.value.plan.parentOID,
//   // projectotype:projectDetail.value.plan.parentOTYPE,
// },
//       changeReason:"",
// }
//     if(isbtn === "恢复启动"){
//       postOAData(params)
//         .then((res) => {
//           window.open(`${res.data.data}`, "_blank");
//         })
//         .catch((error) => {
//           {
//             console.error("获取数据失败:", error);
//             this.$message.error("数据有误，请稍后重试");
//             // 如果接口失败，保持空数组
//           }
//         });

//       isbtn = "";
//     }
//     if(isbtn === "暂停"){
//       postOAData(params)
//         .then((res) => {
//           window.open(`${res.data.data}`, "_blank");
//         })
//         .catch((error) => {
//           {
//             console.error("获取数据失败:", error);
//             this.$message.error("数据有误，请稍后重试");
//             // 如果接口失败，保持空数组
//           }
//         });

//       isbtn = "";
//     }
//     }
// );
</script>

<style lang="scss" scoped>
.content {
  height: 40px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .left {
    display: flex;
    align-items: center;
  }
  .operate-content {
    // border: 1px solid $black_10;
    border: 1px solid hsl(0, 0%, 0%,0.1);
    border-radius: 4px;
    display: flex;
    .operate-btn {
      font-size: 12px;
      height: 32px;
      display: flex;
      align-items: center;
      cursor: pointer;
      .icon {
        padding: 0 4px 0 8px;
        font-size: 14px;
      }
      .title {
        padding-right: 8px;
        // border-right: 1px solid $black_10;
         border-right: 1px solid hsl(0, 0%, 0%,0.1);;
      }
    }
    .disable-btn {
      cursor: not-allowed;
    }
    :last-child {
      .title {
        border: none;
      }
    }
  }
}
.tab-content {
  width: 36px;
  height: 18px;
  background: #055dd5;
  border-radius: 6px 0 6px 0;
  font-size: 12px;
  color: #fff;
  text-align: center;
  padding-right: 4px;
  line-height: 18px;
}
.project-switch-content {
  width: 310px;
}
.collection-content {
  display: flex;
  .tag {
    padding: 0px 8px;
    height: 20px;
    line-height: 20px;
    text-align: center;
    border-radius: 4px;
    // border: 1px solid $white_0;
    border: 1px solid hsl(0, 0%, 100%,0.1);
  }
  :not(:first-child) {
    margin-left: 8px;
  }
  .total-days-title {
    // color: $black_12;
    color: black;
    font-size: 12px;
  }
  .iconfont {
    cursor: pointer;
  }
}
.content {
  :deep(.el-select__wrapper, .el-tooltip__trigger) {
    border: none !important;
    box-shadow: none !important;
    height: 28px !important;
    // min-height: unset !important;
    // padding: 0px 12px !important;
    .el-select__selection {
      height: 24px;
    }

    .el-select__placeholder {
      // position: unset !important;
      font-size: 14px;
      font-weight: 700;
      color: #262626;
      // padding: 0px 12px;
    }
    .el-select__suffix {
      .el-icon {
        color: #005dd5;
      }
    }
  }
}
.icon-liebiao2 {
  font-size: 14px;
}
.link-span {
  position: relative;
  cursor: pointer;
  bottom: 1px;
}
.list-label {
  display: inline-block;
  width: calc(100% - 20px);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.list-shoucang {
  float: right;
}
.shoucangIcon {
  color: #fa8c14;
}
</style>
<style lang="scss">
.el-select-dropdown__list {
  li {
    padding: 0px 12px;
  }
}
.project-list-option {
  .el-select-dropdown,
  .el-select-dropdown__list {
    min-width: 254px !important;
  }
  .el-popper__arrow {
    display: none !important;
  }
  .el-select-dropdown {
    position: fixed !important;
    background-color: #fff;
    box-shadow:
      0 5px 5px -3px #0000001a,
      0 8px 10px 1px #0000000f,
      0 3px 14px 2px #0000000d;
  }
}

.el-popper.is-dark.displayname-tooltip {
  z-index: 99999 !important;
}
</style>
